package edu.office.applicationRepository;

import edu.office.entities.Major;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Named;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

@Named("majorRepositoryA")
@ApplicationScoped
public class MajorRepository extends ApplicationCommonRepository<Major> {

    List<Major> allMajors = new LinkedList<>();
    HashMap<Integer, Major> majorHashMap = new HashMap<>();
    HashMap<Integer, List<Major>> parentHashMajor = new HashMap<>();

    public String myCreate(Major major) {
        //1. check whether the name existed? If true, deny the operation;else continue;
        if (find("NAME", major.getNAME()).list().isEmpty()) {
            create(major);
            return "Succeed";
        } else {
            return major.getNAME() + ": Already Exist";
        }
    }

    public List<Major> getAllList() {
        if (allMajors.isEmpty()) {
            allMajors = findAll().list();
        }
        return allMajors;
    }

    public HashMap<Integer, Major> getIdMap() {
        if (majorHashMap.isEmpty()) {
            getAllList().forEach(major -> {
                majorHashMap.put(major.getID(), major);
            });
        }
        return majorHashMap;
    }

    //其中key为父id
    public HashMap<Integer, List<Major>> getParentHashMajor() {
        if (parentHashMajor.isEmpty()) {
            getAllList().forEach(major -> {
                if (parentHashMajor.get(major.getPARENT()) == null)
                    parentHashMajor.put(major.getPARENT(), new LinkedList<>());
                parentHashMajor.get(major.getPARENT()).add(major);
            });
        }
        return parentHashMajor;
    }
}
